import { createRouter, createWebHashHistory } from "vue-router";
import Login from "/@/pages/Login.vue";
import Layout from "/@/pages/Layout.vue"
import store from "/@/store";

const history = createWebHashHistory();
const router = createRouter({
    history,
    routes: [
        {
            path: "/",
            component: Login
        },
        {
            path: "/admin",
            name: "admin",
            component: Layout,
            beforeEnter: (to, form, next) => {
                const token = localStorage.getItem("token");
                if (token && token !== undefined) {
                    if (to.path === "/") {
                      next({path: "/admin"})
                    } else if(Object.keys(store.state.admin.user).length === 0) {
                        store.dispatch('admin/setUser').then(() => {
                            next();
                        })
                    } else {
                        next();
                    }
                  } else {
                    next({
                      path: "/"
                    })
                }
            },
            children: [
                {
                    path: "",
                    name: "home",
                    component: () => import("../pages/Home.vue"),
                    beforeEnter(to, from, next){
                        store.dispatch("hotel/setHotel").then(() => {
                            next();
                        })
                    }
                },
                {
                    path: "room/all",
                    name: "room/all",
                    component: () => import("../pages/AllRoom.vue"),
                    beforeEnter(to, from, next){
                        Promise.all([
                            store.dispatch("room/setType")
                        ]).then(() => {
                            next()
                        })
                    }
                },
                {
                    path: "room/add",
                    name: "room/add",
                    component: () => import("../pages/AddRoom.vue"),
                    beforeEnter(to, from, next){
                        let promises = [];
                        if(store.state.room.type.length == 0){
                            promises.push(store.dispatch("room/setType"))
                        }

                        Promise.all(promises).then(() => {
                            next();
                        })
                    }
                },
                {
                    path: "room/type",
                    name: "room/type",
                    component: () => import("../pages/AddRoomType.vue")
                },
                {
                    path: "order/all",
                    name: "order/all",
                    component: () => import("../pages/AllOrder.vue")
                }
            ]
        }
    ]
})

export default router;